package com.haixiaoke.saas.order.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.IdcardUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.haixiaoke.saas.auth.ali.service.AliAuthService;
import com.haixiaoke.saas.common.constant.LockConstants;
import com.haixiaoke.saas.common.exception.ServiceException;
import com.haixiaoke.saas.common.tenant.TenantContext;
import com.haixiaoke.saas.common.utils.DateUtils;
import com.haixiaoke.saas.houseMember.domain.HouseMember;
import com.haixiaoke.saas.houseMember.service.IHouseMemberService;
import com.haixiaoke.saas.lock.domain.HouseLock;
import com.haixiaoke.saas.lock.domain.LockFace;
import com.haixiaoke.saas.lock.service.IHouseLockService;
import com.haixiaoke.saas.lock.service.ILockFaceService;
import com.haixiaoke.saas.order.domain.Order;
import com.haixiaoke.saas.order.domain.OrderLessee;
import com.haixiaoke.saas.order.mapper.OrderLesseeMapper;
import com.haixiaoke.saas.order.service.IOrderLesseeService;
import com.haixiaoke.saas.order.service.IOrderService;
import com.haixiaoke.saas.order.state.server.IOrderStateServerRole;
import com.haixiaoke.saas.order.state.server.OrderStateServerRole;
import com.haixiaoke.saas.system.framework.security.util.SecurityUtils;
import com.haixiaoke.saas.user.domain.UserConsumer;
import com.haixiaoke.saas.user.service.IUserConsumerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 订单承租者信息Service业务层处理
 *
 * @author qixi
 * @date 2024-04-03
 */
@Service
public class OrderLesseeServiceImpl implements IOrderLesseeService {
    @Autowired
    private OrderLesseeMapper orderLesseeMapper;
    @Autowired
    private AliAuthService aliAuthService;
    @Autowired
    private IOrderService orderService;
    @Autowired
    private IHouseMemberService houseMemberService;
    @Autowired
    private IUserConsumerService userConsumerService;
    @Autowired
    private ILockFaceService lockFaceService;
    @Autowired
    private IHouseLockService houseLockService;

    /**
     * 查询订单承租者信息
     *
     * @param lesseeId 订单承租者信息主键
     * @return 订单承租者信息
     */
    @Override
    public OrderLessee selectOrderLesseeByLesseeId(Long lesseeId) {
        OrderLessee orderLessee = orderLesseeMapper.selectOrderLesseeByLesseeId(lesseeId);
        String idCardImgs = orderLessee.getCardImgs();
        if (StrUtil.isNotBlank(idCardImgs)) {
            List<String> stringList = StrUtil.split(idCardImgs, ',');
            orderLessee.setCardImgsList(stringList);
        }

        return orderLessee;
    }

    /**
     * 查询订单承租者信息列表
     *
     * @param orderLessee 订单承租者信息
     * @return 订单承租者信息
     */
    @Override
    public List<OrderLessee> selectOrderLesseeList(OrderLessee orderLessee) {
        List<OrderLessee> orderLessees = orderLesseeMapper.selectOrderLesseeList(orderLessee);
        orderLessees.forEach(x -> {
            String idCardImgs = x.getCardImgs();
            if (StrUtil.isNotBlank(idCardImgs)) {
                List<String> stringList = StrUtil.split(idCardImgs, ',');
                x.setCardImgsList(stringList);
            }
        });
        return orderLessees;
    }

    /**
     * 新增订单承租者信息
     *
     * @param orderLessee 订单承租者信息
     * @return 结果
     */
    @Override
    public int insertOrderLessee(OrderLessee orderLessee) {
        orderLessee.setCreateTime(DateUtils.getNowDate());
        List<String> cardImgsList = orderLessee.getCardImgsList();
        if (CollectionUtil.isNotEmpty(cardImgsList)) {
            String join = CollectionUtil.join(cardImgsList, ",");
            orderLessee.setCardImgs(join);
        }

        if (OrderLessee.LESSEE_TYPE_PERSONAL.equals(orderLessee.getLesseeType())) {
            int genderByIdCard = IdcardUtil.getGenderByIdCard(orderLessee.getCardNumber());
            // genderByIdCard  1男  2女
            orderLessee.setLesseeSex(genderByIdCard == 1 ? OrderLessee.LESSEE_SEX_MAN : OrderLessee.LESSEE_SEX_WOMAN);
        }
        return orderLesseeMapper.insertOrderLessee(orderLessee);
    }

    /**
     * 修改订单承租者信息
     *
     * @param orderLessee 订单承租者信息
     * @return 结果
     */
    @Override
    public int updateOrderLessee(OrderLessee orderLessee) {
        orderLessee.setUpdateTime(DateUtils.getNowDate());
        orderLessee.setUpdateBy(SecurityUtils.getUsername());
        List<String> cardImgsList = orderLessee.getCardImgsList();
        if (CollectionUtil.isNotEmpty(cardImgsList)) {
            String join = CollectionUtil.join(cardImgsList, ",");
            orderLessee.setCardImgs(join);
        }
        return orderLesseeMapper.updateOrderLessee(orderLessee);
    }

    /**
     * 批量删除订单承租者信息
     *
     * @param lesseeIds 需要删除的订单承租者信息主键
     * @return 结果
     */
    @Override
    public int deleteOrderLesseeByLesseeIds(Long[] lesseeIds) {
        return orderLesseeMapper.deleteOrderLesseeByLesseeIds(lesseeIds);
    }

    /**
     * 删除订单承租者信息信息
     *
     * @param lesseeId 订单承租者信息主键
     * @return 结果
     */
    @Override
    public int deleteOrderLesseeByLesseeId(Long lesseeId) {
        return orderLesseeMapper.deleteOrderLesseeByLesseeId(lesseeId);
    }

    @Override
    public int rentingTerminationByOrderId(String orderId) {
        return orderLesseeMapper.rentingTerminationByOrderId(orderId);
    }

    @Override
    public int rentingTerminationByOrderIds(List<String> orderIds) {
        return orderLesseeMapper.rentingTerminationByOrderIds(orderIds);
    }

    @Override
    public OrderLessee selectOrderLesseeByOrderId(String orderId) {
        OrderLessee orderLessee = orderLesseeMapper.selectOrderLesseeByOrderId(orderId);
        if (ObjectUtil.isNotNull(orderLessee)) {
            String idCardImgs = orderLessee.getCardImgs();
            if (StrUtil.isNotBlank(idCardImgs)) {
                List<String> stringList = StrUtil.split(idCardImgs, ',');
                orderLessee.setCardImgsList(stringList);
            }
        }
        return orderLessee;
    }


    /**
     * 新增承租者信息
     */
    @Override
    @Transactional
    public int addOrderLessee(OrderLessee orderLessee) {
        Order order = orderService.selectOrderById(orderLessee.getOrderId());
        if (ObjectUtil.isEmpty(order)) {
            throw new ServiceException("订单不存在");
        }
        List<Order> orderList = orderService.selectOrderByHouseIdAndCheckIn(order.getHouseId());
        if (CollectionUtil.isNotEmpty(orderList)) {
            throw new ServiceException("房间已有租客入住");
        }
        if (OrderLessee.LESSEE_TYPE_PERSONAL.equals(orderLessee.getLesseeType())) {
            Boolean flag = aliAuthService.identityCheck(orderLessee.getLesseeName(), orderLessee.getCardNumber());
            if (!flag) {
                throw new ServiceException("身份证号与姓名不匹配");
            }
        } else {
            if (StrUtil.isNotBlank(orderLessee.getHouseManagerName()) && StrUtil.isNotBlank(orderLessee.getCardNumber())) {
                Boolean flag = aliAuthService.identityCheck(orderLessee.getHouseManagerName(), orderLessee.getCardNumber());
                if (!flag) {
                    throw new ServiceException("身份证号与姓名不匹配");
                }
            }
        }

        if (OrderLessee.LESSEE_TYPE_PERSONAL.equals(orderLessee.getLesseeType())) {
            int genderByIdCard = IdcardUtil.getGenderByIdCard(orderLessee.getCardNumber());
            // genderByIdCard  1男  2女
            orderLessee.setLesseeSex(genderByIdCard == 1 ? OrderLessee.LESSEE_SEX_MAN : OrderLessee.LESSEE_SEX_WOMAN);
        }
        orderLessee.setHouseId(order.getHouseId());
        orderLessee.setTenantId(TenantContext.getTenantId());
        orderLessee.setLesseeState(OrderLessee.LESSEE_STATE_AFOOT);
        orderLessee.setCreateTime(DateUtils.getNowDate());



        if (OrderLessee.LESSEE_TYPE_PERSONAL.equals(orderLessee.getLesseeType())) {
            HouseMember houseMember = new HouseMember();
            houseMember.setTenantId(order.getTenantId());
            houseMember.setDeptId(order.getDeptId());
            houseMember.setHouseId(order.getHouseId());
            houseMember.setMemberType(HouseMember.MEMBER_TYPE_TENANTRY);
            houseMember.setMemberName(orderLessee.getLesseeName());
            houseMember.setMemberPhone(orderLessee.getPhone());
            houseMember.setMemberState("1");
            houseMember.setIdCard(orderLessee.getCardNumber());
            houseMember.setOrderId(order.getOrderId());
            houseMember.setSex(orderLessee.getLesseeSex());
            houseMember.setCreateTime(DateUtils.getNowDate());
            houseMemberService.insertHouseMember(houseMember);
        } else {
            HouseMember member = new HouseMember();
            if (StrUtil.isNotBlank(orderLessee.getCardNumber())) {
                int genderByIdCard = IdcardUtil.getGenderByIdCard(orderLessee.getCardNumber());
                // genderByIdCard  1男  2女
                member.setSex(genderByIdCard == 1 ? OrderLessee.LESSEE_SEX_MAN : OrderLessee.LESSEE_SEX_WOMAN);
            }

            member.setTenantId(order.getTenantId());
            member.setDeptId(order.getDeptId());
            member.setHouseId(order.getHouseId());
            member.setMemberType(HouseMember.MEMBER_TYPE_ROOM_MANAGER);
            member.setMemberName(orderLessee.getHouseManagerName());
            member.setMemberPhone(orderLessee.getHouseManagerPhone());
            member.setMemberState("1");
            member.setIdCard(orderLessee.getCardNumber());
            member.setOrderId(order.getOrderId());
            member.setCreateTime(DateUtils.getNowDate());
            houseMemberService.insertHouseMember(member);

        }

        if (OrderLessee.LESSEE_TYPE_ENTERPRISE.equals(orderLessee.getLesseeType())) {
            orderLessee.setCardNumber(null);
        }
        orderLesseeMapper.insertOrderLessee(orderLessee);
        IOrderStateServerRole orderStateServerRole = new OrderStateServerRole(order);
        orderStateServerRole.sign();


        // 删除房管员人脸授权信息
        List<LockFace> lockFaceList = lockFaceService.selectLockFaceListAndHouseIdAndUserTypeAndFaceState(order.getHouseId(), LockConstants.USER_TYPE_MANAGER, LockConstants.FACE_STATE_ENABLED);
        if (CollectionUtil.isNotEmpty(lockFaceList)) {
            for (LockFace lockFace : lockFaceList) {
                HouseLock houseLock = new HouseLock();
                houseLock.setMac(lockFace.getMac());
                houseLockService.disableLockFaceAndFaceState(houseLock, lockFace);
            }
        }

        return 1;
    }

    @Override
    public int updateOrderLesseeByOrderId(String orderId, String houseId) {
        return orderLesseeMapper.updateOrderLesseeByOrderId(orderId, houseId);
    }
}
